package com.spider.admin.utils;

import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class CommonUtil {
    /**
     * 获取唯一Key
     * 生成UUID，字符长度32位
     *
     * @return
     */
    public static String getUniqueKey() {
        return StringUtils.remove(UUID.randomUUID().toString(), "-");
    }

    /**
     * 生成唯一ID值，10万次以内出现重复几率1~5次，数据量大约10万次不建议使用
     *
     * @return
     */
    public static String getShortUniqueId() {
        return new String(Base64.getEncoder().encode(Integer.toString(Long.toString(UUID.randomUUID().getMostSignificantBits()).hashCode()).getBytes()));
    }


    public static String md5(String plainString) {
        String cipherString = null;
        try {
            // 获取实例
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            // 计算摘要
            byte[] cipherBytes = messageDigest.digest(plainString.getBytes(StandardCharsets.UTF_8));
            // 输出为16进制字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : cipherBytes) {
                sb.append(String.format("%02x", b));
            }
            cipherString = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cipherString;
    }

    public static String generatePassword(int length) {
        String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789@#$";
        SecureRandom RANDOM = new SecureRandom();
        if (length <= 0) {
            throw new IllegalArgumentException("Length must be a positive integer.");
        }
        StringBuilder password = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = RANDOM.nextInt(CHAR_SET.length());
            password.append(CHAR_SET.charAt(index));
        }
        return password.toString();
    }

    public static String getCurrentDate(String format) {
        format = StringUtils.isEmpty(format) ? "yyyy-MM-dd HH:mm:ss" : format;
        SimpleDateFormat sf = new SimpleDateFormat(format);
        return sf.format(new Date());
    }

    public static String getRuntimeIP() {
        String ip = "";
        try {
            ip = Inet4Address.getLocalHost().getHostAddress();
        } catch (Exception e) {
            try {
                ip = Inet6Address.getLocalHost().getHostAddress();
            } catch (Exception e1) {
            }
        }
        return ip;
    }

    public static void main(String[] args) {

        System.out.println(CommonUtil.getRuntimeIP());
    }
}
